package com.wyj.service.imp;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.wyj.mapper.DiscussPostMapper;
import com.wyj.pojo.DiscussPost;
import com.wyj.service.DiscussPostService;
import com.wyj.util.SensitiveFilter;
import lombok.extern.log4j.Log4j2;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Log4j2
@Service
public class DiscussPostServiceImp implements DiscussPostService {

    @Autowired
    DiscussPostMapper discussPostMapper;
    @Autowired
    SensitiveFilter sensitiveFilter;

    @Value("${caffeine.gets.max-size}")
    private int maxSize;

    @Value("${caffeine.gets.expire-seconds}")
    private int expireSeconds;

    //帖子列表 缓存
    private LoadingCache<String,List<DiscussPost>> postListCache;

    //帖子总数的缓存
    private LoadingCache<Integer,Integer> postRowsCache;


    @PostConstruct
    public void init() {
        //初始化帖子的列表
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.MINUTES)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    @Override
                    public @Nullable List<DiscussPost> load(String key) throws Exception {
                        if (key == null || key.length() == 0) {
                            throw new IllegalArgumentException("参数错误");
                        }

                        //将key取出来
                        String[] params = key.split(":");
                        if (params == null  || params.length == 0) {
                            throw  new IllegalArgumentException("参数 为空");
                        }

                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);

                        //可以设置二级缓存  当我们查询本地缓存没有的时候  我们可以查询 二级缓存
                        log.info("load info is .DB");
                        return discussPostMapper.selectDiscussPosts(0,limit,offset,1);
                    }
                });
        //初始化帖子总数
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Nullable
                    @Override
                    public Integer load(@NonNull Integer key) throws Exception {
                        log.debug("load post rows from DB.");
                        return discussPostMapper.selectDiscussPostRows(key);
                    }
                });
    }

    @Override
    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit,int modelOpt) {
        //userId = 0 就是查询所有的帖子
        if (userId == 0 && modelOpt == 1) {
           return postListCache.get(offset + ":" + limit);
        }
        log.info("查询不是最热帖子时候  从数据库中进行查询");
        return discussPostMapper.selectDiscussPosts(userId, offset, limit,modelOpt);
    }

    @Override
    public int findDiscussPostRows(int userId) {
        if(userId == 0) {
         return postRowsCache.get(userId);
        }

        log.info("从数据库中进行查询");
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    @Override
    public int addDiscussPost(DiscussPost discussPost) {

        //判空处理
        if (discussPost == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        //html转义 防止在输入框 故意 输入一些脚本数据
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));

        //敏感词过滤
        discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
        discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));


        return discussPostMapper.insertDiscussPost(discussPost);
    }

    @Override
    public DiscussPost getDiscussPost(int id) {
        return discussPostMapper.getDiscussPostById(id);
    }

    @Override
    public int updateDiscussPostReplies(int id, int commentCount) {
        return discussPostMapper.updateDiscussPostReplies(id,commentCount);
    }

    @Override
    public int updateDiscussPostScore(int id, double score) {
        return discussPostMapper.updateDiscussPostScore(id,score);
    }

}
